package fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jianke.R;
import com.jianke.R2;
import com.lib.app.CodeUtil;
import com.lib.app.EventBusTagUtils;
import com.lib.bean.Event;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import bean.ChooseDataBean;
import bean.GradeBean;
import bean.SubjectBean;
import butterknife.BindView;
import butterknife.OnClick;

public class ChooseFragment extends BaseAppFragment {


    @BindView(R2.id.recy_grade)
    RecyclerView recyGrade;
    @BindView(R2.id.recy_class)
    RecyclerView recyClass;
    @BindView(R2.id.tv_cancelChoose)
    TextView tvCancelChoose;
    @BindView(R2.id.tv_sureChoose)
    TextView tvSureChoose;
    @BindView(R2.id.lin_transparent)
    LinearLayout linTransparent;

    @BindView(R2.id.btn_tuozhan)
    Button btnTuoZhan;

    private boolean btnClicked = true;

    CourseAdapter courseAdapter;
    //创建学科数据源
    private String[] course = {
            "语文", "数学", "英语",
            "化学", "地理", "生物", "历史", "物理",
            "政治"
    };
    private List<Button> btnCourseList = new ArrayList<>();
    private List<String> mDataCourse = new ArrayList<>();

    GradeAdapter gradeAdapter;
    //创建年级数据源
    private String[] grade = {"一年级", "二年级", "三年级",
            "四年级", "五年级", "六年级",
            "初一", "初二", "初三",
            "高一", "高二", "高三"};
    private List<Button> btnGradeList = new ArrayList<>();
    private List<String> mDataGrade = new ArrayList<>();

    //装载年级的实体类和字符串
    private GradeBean gradeBean;
    private String chooseGrade = "";

    //装载科目的实体类和字符串
    private SubjectBean subjectBean;
    private String chooseSubject = "";

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        //初始化拓展按钮
        initTuoZhanBtn();

        //初始化年级容器数据和适配器
        initGradeList();
        initGradeData();

        //初始化科目容器数据和适配器
        initCourseList();
        initCourseData();

    }

    private void initTuoZhanBtn() {

        btnTuoZhan.setBackgroundResource(R.drawable.bg_circle_hollow_r22_1);
        btnTuoZhan.setTextColor(getResources().getColor(R.color.base_text1));

    }

    @OnClick({R2.id.tv_cancelChoose, R2.id.tv_sureChoose, R2.id.lin_transparent, R2.id.btn_tuozhan})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_cancelChoose) {

            EventBus.getDefault().post(new Event<>(1, "隐藏年级学科选择"), EventBusTagUtils.ChooseFragment);

        } else if (i == R.id.tv_sureChoose) {

            if ("".equals(chooseSubject) && "".equals(chooseGrade)) {
                showToast("请选择年级或者学科之后再筛选");
                return;
            } else {

                ChooseDataBean dataBean = new ChooseDataBean();
                if ("".equals(chooseGrade)) {
                    LogUtil.e("筛选年级为空，选择的科目为：" + chooseSubject);
                    String subjectId = getSubjectId(subjectBean, chooseSubject);
                    dataBean.setCourse(subjectId);
                } else if ("".equals(chooseSubject)) {
                    LogUtil.e("筛选科目为空，选择的年级为：" + chooseGrade);
                    String gradeId = getGradeId(gradeBean, chooseGrade);
                    dataBean.setGrade(gradeId);

                } else {
                    LogUtil.e("选择的科目是：" + chooseSubject + "，选择的年级是：" + chooseGrade);

                    String gradeId = getGradeId(gradeBean, chooseGrade);
                    String subjectId = getSubjectId(subjectBean, chooseSubject);
                    LogUtil.e("选择的科目的Id是：" + subjectId + "，选择的年级的Id是：" + gradeId);

                    //将选择的年级科目String字符串转换为相对应的Id
                    dataBean.setGrade(gradeId);
                    dataBean.setCourse(subjectId);
                }

                EventBus.getDefault().post(new Event<>(1, dataBean), EventBusTagUtils.SureChooseRefresh);

                EventBus.getDefault().post(new Event<>(1, "隐藏年级学科选择"), EventBusTagUtils.ChooseFragment);

            }

        } else if (i == R.id.lin_transparent) {

            EventBus.getDefault().post(new Event<>(1, "隐藏年级学科选择"), EventBusTagUtils.ChooseFragment);
        } else if (i == R.id.btn_tuozhan) {

            if (btnClicked) {

                btnTuoZhan.setBackgroundResource(R.drawable.bg_circle_bule_r22_1);
                btnTuoZhan.setTextColor(getResources().getColor(R.color.white));

                btnClicked = false;

            } else {

                btnTuoZhan.setBackgroundResource(R.drawable.bg_circle_hollow_r22_1);
                btnTuoZhan.setTextColor(getResources().getColor(R.color.base_text1));

                btnClicked = true;
            }

        }
    }


    /**
     * 将String科目字符串转为相对应的科目Id
     *
     * @param subjectBean
     * @param str
     * @return
     */
    private String getSubjectId(SubjectBean subjectBean, String str) {

        for (int i = 0; i < subjectBean.getObj().size(); i++) {
            if (str.equals(subjectBean.getObj().get(i).getName())) {
                return subjectBean.getObj().get(i).getId();
            }
        }

        return null;
    }

    /**
     * 将String年级字符串转为相对应的年级Id
     *
     * @param gradeBean
     * @param str
     * @return
     */
    private String getGradeId(GradeBean gradeBean, String str) {

        for (int i = 0; i < gradeBean.getObj().size(); i++) {
            if (str.equals(gradeBean.getObj().get(i).getName())) {
                return gradeBean.getObj().get(i).getId();
            }
        }

        return null;
    }

    private void initCourseData() {

        courseAdapter = new CourseAdapter(getContext(), mDataCourse);
        recyClass.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyGrade.setNestedScrollingEnabled(false);
        recyClass.setAdapter(courseAdapter);

    }


    private void initCourseList() {
        mDataCourse.clear();
        HttpUtils.with(getActivity())
                .addParam("requestType", "DICT_SUBJECT_LIST")
                .execute(new HttpNormalCallBack<SubjectBean>() {
                    @Override
                    public void onSuccess(SubjectBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {
                            subjectBean = result;

                            for (int i = 0; i < result.getObj().size(); i++) {
                                mDataCourse.add(result.getObj().get(i).getName());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }


    private void initGradeData() {

        gradeAdapter = new GradeAdapter(getContext(), mDataGrade);
        recyGrade.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyGrade.setNestedScrollingEnabled(false);
        recyGrade.setAdapter(gradeAdapter);

    }

    private void initGradeList() {
        mDataGrade.clear();
        HttpUtils.with(getActivity())
                .addParam("requestType", "DICT_GRADE_LIST")
                .execute(new HttpNormalCallBack<GradeBean>() {
                    @Override
                    public void onSuccess(GradeBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {
                            gradeBean = result;

                            for (int i = 0; i < result.getObj().size(); i++) {
                                mDataGrade.add(result.getObj().get(i).getName());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_choose;
    }


    public class GradeAdapter extends BaseAdapter<String> {

        public GradeAdapter(Context context, List<String> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_book;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, final int position, final List<String> mData) {

            final Button btn_text = holder.getView(R.id.btn_text);
            btnGradeList.add(btn_text);
            btn_text.setText(mData.get(position));
            btn_text.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onClick(View v) {

                    initGradeButton();

                    btn_text.setBackgroundResource(R.drawable.bg_circle_bule_r22_1);
                    btn_text.setTextColor(getResources().getColor(R.color.white));

                    chooseGrade = mData.get(position);

                }


            });

        }
    }

    private void initGradeButton() {
        for (Button button : btnGradeList) {
            button.setBackgroundResource(R.drawable.bg_circle_hollow_r22_1);
            button.setTextColor(getResources().getColor(R.color.base_text1));
        }

    }


    public class CourseAdapter extends BaseAdapter<String> {

        public CourseAdapter(Context context, List<String> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_book;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, final int position, final List<String> mData) {

            final Button btn_text = holder.getView(R.id.btn_text);
            btnCourseList.add(btn_text);
            btn_text.setText(mData.get(position));
            btn_text.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onClick(View v) {

                    initCourseButton();

                    btn_text.setBackgroundResource(R.drawable.bg_circle_bule_r22_1);
                    btn_text.setTextColor(getResources().getColor(R.color.white));

                    chooseSubject = mData.get(position);
                }

            });

        }
    }

    private void initCourseButton() {
        for (Button button : btnCourseList) {
            button.setBackgroundResource(R.drawable.bg_circle_hollow_r22_1);
            button.setTextColor(getResources().getColor(R.color.base_text1));
        }
    }

    private ChooseSubjectGradeListener chooseListener;

    public interface ChooseSubjectGradeListener {

        void comfirmChoose(String grade, String subject);
    }

    public void setChooseSubjectGradeListener(ChooseSubjectGradeListener chooseListener) {

        this.chooseListener = chooseListener;
    }

}
